import 'package:flutter/material.dart';

class StreamBuilderCounter extends StatefulWidget {
  const StreamBuilderCounter({super.key});

  @override
  State<StreamBuilderCounter> createState() => _StreamBuilderState();
}

class _StreamBuilderState extends State<StreamBuilderCounter> {
  Stream<int> counter() {
    return Stream.periodic(const Duration(seconds: 3), (count) {
      return count;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Title'),
      ),
      body: StreamBuilder(
          stream: counter(),
          builder: (context, snapshot) {
            // 观察ConnectionState的状态
            print('snapshot.connectionState:${snapshot.connectionState}');
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return const Center(
                  child: Text("NONE: 没有数据流"),
                );
              case ConnectionState.waiting:
                return const Center(child: Text("WAITING: 等待数据流"));
              case ConnectionState.active:
                if (snapshot.hasError) {
                  return Center(
                      child: Text("ACTIVE: 数据流活跃，异常: ${snapshot.error}"));
                } else {
                  return Center(
                      child: Text("ACTIVE: 数据流活跃，数据: ${snapshot.data}"));
                }
              case ConnectionState.done:
                return const Center(child: Text("DONE: 数据流关闭"));
              default:
                throw "ConnectionState没有别的状态";
            }
          }),
    );
  }
}
